<template>
    <a-card hoverable>
        <!-- <p>
        <b>{{$t('System')}} IOPS</b>
    </p> -->
        <a-modal v-model="visible" title="自定义时间范围" @ok="handleOk" v-dragModal>
            <a-date-picker v-model="startValue" show-time placeholder="Select Time" :disabled-date="disabledStartDate" />
            -- <a-date-picker v-model="endValue" :disabled-date="disabledEndDate" show-time @ok="onOk"
                :default-value="moment(new Date(), 'YYYY-MM-DD HH:MM:SS')" />
        </a-modal>
        <!-- <a-radio-group style="margin-bottom: 0.5rem" @change="getHistory" v-model="value" button-style="solid">
        <a-radio-button value="realtime">
          {{$t('Real_time')}}
        </a-radio-button>
        <a-radio-button value="hour">
          {{$t('Nearly_one_hour')}}
        </a-radio-button>
        <a-radio-button value="day">
          {{$t('Nearly_one_day')}}
        </a-radio-button>
        <a-radio-button value="week">
          {{$t('Nearly_one_week')}}
        </a-radio-button>
        <a-radio-button value="month">
          {{$t('Nearly_one_month')}}
        </a-radio-button>
        <a-radio-button value="auto">
          {{$t('Custom')}}
        </a-radio-button>
      </a-radio-group> -->
        <a-spin :spinning="chartLoading">
            <div id="iops" style="width: 100%;height:210px; margin-bottom: 1rem"></div>
            <!-- <p>
            <b>{{$t('System')}} MBPS（B/s）</b>
        </p> -->
            <div id="mbps" style="width: 100%;height:210px; margin-bottom: 1rem"></div>
            <!-- <p>
            <b>{{$t('System')}} {{$t('Delay')}}（ms）</b>
        </p> -->
            <div id="systime" style="width: 100%;height:210px; margin-bottom: 1rem"></div>
        </a-spin>
    </a-card>
</template>

<script>
// import DataSet from "@antv/data-set";
import moment from 'moment';
import * as echarts from 'echarts';
import { step_max_getter } from '../../untils/step'
import request from '@/request/request'
export default {
    name: "Charts",
    data() {
        return {
            //       iopsdata: [{time: 0, ips: 10, ops: 3},
            // {time: 1, ips: 11, ops: 3},
            // {time: 2, ips: 13, ops: 3},
            // {time: 3, ips: 16, ops: 3},
            // {time: 4, ips: 10, ops: 3},
            // {time: 5, ips: 2, ops: 3},
            // {time: 6, ips: 3, ops: 3},
            // {time: 7, ips: 7, ops: 3},
            // {time: 8, ips: 8, ops: 3},
            // {time: 9, ips: 9, ops: 3},
            // {time: 10, ips: 1, ops: 3},
            // {time: 11, ips: 2, ops: 3},
            // {time: 12, ips: 3, ops: 3},
            // {time: 13, ips: 4, ops: 3},
            // {time: 14, ips: 8, ops: 3},
            // {time: 15, ips: 6, ops: 3},
            // {time: 16, ips: 12, ops: 3},
            // {time: 17, ips: 25, ops: 3},
            // {time: 18, ips: 44, ops: 3},
            // {time: 19, ips: 33, ops: 3}],
            iopsdata: [],
            mbpsdata: [],
            sysdata: [],
            myChart1: '',
            myChart2: '',
            myChart3: '',
            value: 'realtime',
            visible: false,
            startValue: null,
            endValue: moment(new Date(), 'YYYY-MM-DD HH:MM:SS'),
            chartLoading: true,
            timer: null,
        };
    },
    created() {
        // this.initWebSocket();
    },
    async mounted() {
        this.getList()
        this.timer = setInterval(() => this.getList(), 2000)
        //再初始化之后调整图表的大小自适应
        // const e = document.createEvent("Event");
        // e.initEvent("resize", true, true);
        // window.dispatchEvent(e);
        // this.echartiops() //echart IOPS
        // }
        // test
    },
    beforeDestroy() {
        clearInterval(this.timer)
        this.timer = null
        // 关闭页面之前断开ws连接
        //   this.wsclose();
    },

    watch: {
        "$store.state.language"() {
            let IOPSNewOption = this.myChart1 && this.myChart1.getOption();
            let MBPSNewOption = this.myChart2 && this.myChart2.getOption();
            let delayNewOption = this.myChart3 && this.myChart3.getOption();
            IOPSNewOption.title[0].text = this.$t('System') + ' ' + 'IOPS';
            MBPSNewOption.title[0].text = this.$t('System') + ' ' + 'MBPS';
            delayNewOption.title[0].text = this.$t('System') + ' ' + this.$t('Delay') + '（ms）';
            this.myChart1.setOption({ ...IOPSNewOption });
            this.myChart2.setOption({ ...MBPSNewOption });
            this.myChart3.setOption({ ...delayNewOption });
        },
    },

    methods: {
        moment,
        async getList() {
            const { data } = await request('get', 'index/realtime')
            this.iopsdata = data.iops;
            if (this.myChart1 != null && this.myChart1 != '' && this.myChart1 != undefined) {
                // this.myChart1.dispose();//销毁
                this.myChart1.setOption({
                    dataset: {
                        source: this.iopsdata
                    },
                });
                window.addEventListener("resize", () => { this.myChart1.resize() });
            } else {
                this.echartiops() //echart IOPS
            }
            this.mbpsdata = data.mbps;
            if (this.myChart2 != null && this.myChart2 != '' && this.myChart2 != undefined) {
                // this.myChart1.dispose();//销毁
                this.myChart2.setOption({
                    dataset: {
                        source: this.mbpsdata
                    },
                });
                window.addEventListener("resize", () => { this.myChart2.resize() });
            } else {
                this.echartmbps() //echart IOPS
            }
            this.sysdata = data.delay;
            if (this.myChart3 != null && this.myChart3 != '' && this.myChart3 != undefined) {
                // this.myChart1.dispose();//销毁
                this.myChart3.setOption({
                    dataset: {
                        source: this.sysdata
                    },
                });
                window.addEventListener("resize", () => { this.myChart3.resize() });
            } else {
                this.echartdelay() //echart IOPS
            }
            this.chartLoading = false;
        },
        handleOk(e) {
            this.visible = false;
            this.getHistoryData(this.startValue.valueOf() / 1000, this.endValue.valueOf() / 1000, '1d')
        },
        // onChange(value, dateString) {
        //     console.log('Selected Time: ', value);
        //     console.log('Formatted Selected Time: ', dateString);
        // },
        onOk(value) {
            // console.log('onOk: ', new Date(value).getTime(), new Date().getTime());
        },
        disabledStartDate(startValue) {
            const endValue = this.endValue;
            if (!startValue || !endValue) {
                return false;
            }
            return startValue.valueOf() > endValue.valueOf();
        },
        disabledEndDate(endValue) {
            const startValue = this.startValue;
            if (!endValue || !startValue) {
                return false;
            }
            return startValue.valueOf() >= endValue.valueOf() || endValue.valueOf() > moment(new Date(), 'YYYY-MM-DD HH:MM:SS');
        },
        getHistoryData(start, end, step) {
            request('get', 'history_real_time', {
                // params: {
                start: parseInt(start),
                end: parseInt(end),
                step: step
                // }
            }).then(res => {
                if (res.data.flag == 1) {
                    this.model(res.data.id) //返回模板
                    this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                } else {
                    this.ws.close();
                    this.iopsdata = res.data.iops
                    this.myChart1.setOption({
                        dataset: {
                            source: res.data.iops
                        },
                    });
                    this.myChart2.setOption({
                        dataset: {
                            source: res.data.mbps
                        },
                    });
                    this.myChart3.setOption({
                        dataset: {
                            source: res.data.delay
                        },
                    });
                }
            })
        },
        getHistory(e) {
            let timer = new Date().getTime() / 1000;
            switch (e.target.value) {
                case 'realtime':
                    this.initWebSocket();
                    break;
                case 'hour':
                    this.getHistoryData(timer - 60 * 60, timer, '1m')
                    break;
                case 'day':
                    this.getHistoryData(timer - 24 * 60 * 60, timer, '1h')
                    break;
                case 'week':
                    this.getHistoryData(timer - 7 * 24 * 60 * 60, timer, '1h')
                    break;
                case 'month':
                    this.getHistoryData(timer - 30 * 24 * 60 * 60, timer, '1d')
                    break;
                case 'auto':
                    this.visible = true
                    break;
            }
        },
        // websocket的使用
        initWebSocket() {
            if ("WebSocket" in window) {
                const wsurl = "ws://" + this.wsurl + "/realtime";
                // let authToken = JSON.parse(localStorage.getItem('authToken'));
                this.ws = new WebSocket(wsurl);//'Bearer '+authToken
                this.ws.onopen = this.wsonopen;
                this.ws.onmessage = this.wsonmessage;
                // this.ws.close = this.wsclose;
            } else {
                // 浏览器不支持 WebSocket
                console.log("您的浏览器不支持 WebSocket!");
            }
        },
        //打开链接，发送数据
        wsonopen() {
            console.log("websocket已连接，使用send方法发送数据。。");
        },
        //接收数据
        wsonmessage(evt) {
            let received_msg = JSON.parse(evt.data);
            this.iopsdata = received_msg.iops;
            if (this.myChart1 != null && this.myChart1 != '' && this.myChart1 != undefined) {
                // this.myChart1.dispose();//销毁
                this.myChart1.setOption({
                    dataset: {
                        source: this.iopsdata
                    },
                });
                window.addEventListener("resize", () => { this.myChart1.resize() });
            } else {
                this.echartiops() //echart IOPS
            }
            this.mbpsdata = received_msg.mbps;
            if (this.myChart2 != null && this.myChart2 != '' && this.myChart2 != undefined) {
                // this.myChart1.dispose();//销毁
                this.myChart2.setOption({
                    dataset: {
                        source: this.mbpsdata
                    },
                });
                window.addEventListener("resize", () => { this.myChart2.resize() });
            } else {
                this.echartmbps() //echart IOPS
            }
            this.sysdata = received_msg.delay;
            if (this.myChart3 != null && this.myChart3 != '' && this.myChart3 != undefined) {
                // this.myChart1.dispose();//销毁
                this.myChart3.setOption({
                    dataset: {
                        source: this.sysdata
                    },
                });
                window.addEventListener("resize", () => { this.myChart3.resize() });
            } else {
                this.echartdelay() //echart IOPS
            }
            this.chartLoading = false;
        },
        //关闭连接
        wsclose() {
            this.ws.close();
            console.log("已断开连接");
        },
        echartiops() {
            let chartDom = document.getElementById('iops');
            this.myChart1 = echarts.init(chartDom);
            let option;
            option = {
                title: {
                    text: this.$t('System') + ' ' + 'IOPS',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)',
                        fontSize: 14
                    }
                },
                color: ["#ff549e", "#01f6ff"],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['ips', 'ops']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '22%',
                    containLabel: true
                },
                dataset: {
                    source: this.iopsdata
                },
                xAxis: {
                    type: 'category'
                },
                yAxis: {
                    max: function (value) {
                        return step_max_getter(value.max)
                    },
                    //   minInterval: 1, // 最小刻度
                    //   maxInterval: 1000, // 最大刻度
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [{
                    type: 'line',
                    name: 'ips',
                    smooth: true, //是否平滑
                    showSymbol: false, // 不显示点
                    encode: {
                        // 将 "time" 列映射到 X 轴。
                        x: 'time',
                        // 将 "ips" 列映射到 Y 轴。
                        y: 'ips'
                    }
                }, {
                    type: 'line',
                    name: 'ops',
                    smooth: true, //是否平滑
                    showSymbol: false, // 不显示点
                    encode: {
                        // 将 "time" 列映射到 X 轴。
                        x: 'time',
                        // 将 "ops" 列映射到 Y 轴。
                        y: 'ops'
                    }
                }
                ],
                // 拖拽范围
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: 100
                    }
                ],
            };
            this.myChart1.setOption(option);
            window.addEventListener("resize", () => { this.myChart1.resize() });
        },
        echartmbps() {
            let chartDom = document.getElementById('mbps');
            this.myChart2 = echarts.init(chartDom);
            let option;
            option = {
                title: {
                    text: this.$t('System') + ' ' + 'MBPS',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)',
                        fontSize: 14
                    }
                },
                color: ["#feae03", "#4cbdff"],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['read', 'write']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '22%',
                    containLabel: true
                },
                dataset: {
                    source: this.mbpsdata
                },
                xAxis: {
                    type: 'category'
                },
                yAxis: {
                    max: function (value) {
                        return step_max_getter(value.max)
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [{
                    type: 'line',
                    name: 'read',
                    smooth: true, //是否平滑
                    showSymbol: false, // 不显示点
                    encode: {
                        // 将 "time" 列映射到 X 轴。
                        x: 'time',
                        // 将 "ips" 列映射到 Y 轴。
                        y: 'read'
                    }
                }, {
                    type: 'line',
                    name: 'write',
                    smooth: true, //是否平滑
                    showSymbol: false, // 不显示点
                    encode: {
                        // 将 "time" 列映射到 X 轴。
                        x: 'time',
                        // 将 "ops" 列映射到 Y 轴。
                        y: 'write'
                    }
                }
                ],
                // 拖拽范围
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: 100
                    }
                ],
            };
            this.myChart2.setOption(option);
            window.addEventListener("resize", () => { this.myChart2.resize() });
        },
        echartdelay() {
            let chartDom = document.getElementById('systime');
            this.myChart3 = echarts.init(chartDom);
            let option;
            option = {
                title: {
                    text: this.$t('System') + ' ' + this.$t('Delay') + '（ms）',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)',
                        fontSize: 14
                    }
                },
                dataset: {
                    source: this.sysdata
                },
                xAxis: {
                    type: 'category'
                },
                yAxis: {
                    max: function (value) {
                        return step_max_getter(value.max)
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '22%',
                    containLabel: true
                },
                tooltip: {
                    trigger: 'axis'
                },
                series: [{
                    type: 'line',
                    name: 'value',
                    smooth: true, // 是否平滑线
                    showSymbol: false, // 不显示点
                    encode: {
                        // 将 "time" 列映射到 X 轴。
                        x: 'time',
                        // 将 "ips" 列映射到 Y 轴。
                        y: 'value'
                    },
                    areaStyle: {}
                }],
                // 拖拽范围
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: 100
                    }
                ],
            };
            this.myChart3.setOption(option);
            window.addEventListener("resize", () => { this.myChart3.resize() });
        },
    }
};
</script>
<style scoped>
#iops {
    touch-action: none
}
</style>
